using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using CsvHelper;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using YahooFinanceApi;
using System.Globalization;

namespace VerifyFileCacheCompliance
{
    /// <summary>
    /// Yahoo Finance真实数据下载器
    /// 严格遵守generic-rule.md规则
    /// 所有数据必须来自真实API调用
    /// </summary>
    public class YahooFinanceDataDownloader
    {
        private readonly ILogger<YahooFinanceDataDownloader> _logger;
        private readonly string _dataDirectory;

        public YahooFinanceDataDownloader(ILogger<YahooFinanceDataDownloader> logger)
        {
            _logger = logger;
            _dataDirectory = Path.Combine(Directory.GetCurrentDirectory(), "TestData");

            if (!Directory.Exists(_dataDirectory))
            {
                Directory.CreateDirectory(_dataDirectory);
            }
        }

        /// <summary>
        /// 从Yahoo Finance API下载真实历史数据
        /// </summary>
        public async Task<DownloadResult> DownloadRealDataAsync(
            string symbol,
            DateTime startDate,
            DateTime endDate)
        {
            _logger.LogInformation("========== Yahoo Finance 数据下载 ==========");
            _logger.LogInformation($"正在连接Yahoo Finance API...");
            _logger.LogInformation($"下载 {symbol} 历史数据 ({startDate:yyyy-MM-dd} 至 {endDate:yyyy-MM-dd})...");

            var result = new DownloadResult
            {
                Symbol = symbol,
                StartDate = startDate,
                EndDate = endDate,
                DownloadTime = DateTime.UtcNow
            };

            try
            {
                // 调用Yahoo Finance API获取真实历史数据
                var history = await Yahoo.GetHistoricalAsync(
                    symbol,
                    startDate,
                    endDate,
                    Period.Daily);

                if (history == null || !history.Any())
                {
                    _logger.LogError("API返回空数据");
                    result.Success = false;
                    result.ErrorMessage = "No data returned from API";
                    return result;
                }

                // 转换为我们的数据格式
                var records = new List<YahooDataRecord>();
                foreach (var candle in history)
                {
                    records.Add(new YahooDataRecord
                    {
                        Symbol = symbol,
                        Date = candle.DateTime,
                        Open = candle.Open,
                        High = candle.High,
                        Low = candle.Low,
                        Close = candle.Close,
                        AdjustedClose = candle.AdjustedClose,
                        Volume = candle.Volume
                    });
                }

                result.RecordCount = records.Count;
                result.Records = records;

                // 保存到CSV文件
                var csvFileName = Path.Combine(_dataDirectory, $"{symbol.ToLower()}_yahoo_real.csv");
                await SaveToCsvAsync(records, csvFileName);
                result.CsvFilePath = csvFileName;

                // 保存元数据
                var metadata = new DataMetadata
                {
                    Source = "Yahoo Finance API",
                    DownloadTime = result.DownloadTime,
                    Symbol = symbol,
                    StartDate = startDate.ToString("yyyy-MM-dd"),
                    EndDate = endDate.ToString("yyyy-MM-dd"),
                    RecordCount = result.RecordCount,
                    DataType = "Daily",
                    ApiVersion = "2.1.2"
                };

                var metadataFileName = Path.Combine(_dataDirectory, "data_metadata.json");
                await SaveMetadataAsync(metadata, metadataFileName);

                _logger.LogInformation($"✓ 成功下载 {result.RecordCount} 条交易日数据");
                _logger.LogInformation($"✓ 数据已保存到 {csvFileName}");

                result.Success = true;
                return result;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "下载数据失败");
                result.Success = false;
                result.ErrorMessage = ex.Message;
                return result;
            }
        }

        /// <summary>
        /// 保存数据到CSV文件
        /// </summary>
        private async Task SaveToCsvAsync(List<YahooDataRecord> records, string fileName)
        {
            using var writer = new StreamWriter(fileName);
            using var csv = new CsvWriter(writer);

            csv.WriteHeader<YahooDataRecord>();
            await csv.NextRecordAsync();

            foreach (var record in records)
            {
                csv.WriteRecord(record);
                await csv.NextRecordAsync();
            }
        }

        /// <summary>
        /// 保存元数据
        /// </summary>
        private async Task SaveMetadataAsync(DataMetadata metadata, string fileName)
        {
            var json = JsonConvert.SerializeObject(metadata, Formatting.Indented);
            await File.WriteAllTextAsync(fileName, json);
        }

        /// <summary>
        /// 从CSV文件加载数据（用于验证）
        /// </summary>
        public async Task<List<YahooDataRecord>> LoadFromCsvAsync(string symbol)
        {
            var csvFileName = Path.Combine(_dataDirectory, $"{symbol.ToLower()}_yahoo_real.csv");

            if (!File.Exists(csvFileName))
            {
                _logger.LogError($"CSV文件不存在: {csvFileName}");
                return new List<YahooDataRecord>();
            }

            using var reader = new StreamReader(csvFileName);
            using var csv = new CsvReader(reader);

            var records = new List<YahooDataRecord>();

            // 读取记录
            csv.Read();
            csv.ReadHeader();

            while (csv.Read())
            {
                var record = csv.GetRecord<YahooDataRecord>();
                records.Add(record);
            }

            await Task.CompletedTask;

            _logger.LogInformation($"从CSV加载了 {records.Count} 条记录");
            return records;
        }
    }

    /// <summary>
    /// Yahoo数据记录
    /// </summary>
    public class YahooDataRecord
    {
        public string Symbol { get; set; }
        public DateTime Date { get; set; }
        public decimal Open { get; set; }
        public decimal High { get; set; }
        public decimal Low { get; set; }
        public decimal Close { get; set; }
        public decimal AdjustedClose { get; set; }
        public long Volume { get; set; }
    }

    /// <summary>
    /// 下载结果
    /// </summary>
    public class DownloadResult
    {
        public bool Success { get; set; }
        public string Symbol { get; set; }
        public DateTime StartDate { get; set; }
        public DateTime EndDate { get; set; }
        public DateTime DownloadTime { get; set; }
        public int RecordCount { get; set; }
        public string CsvFilePath { get; set; }
        public string ErrorMessage { get; set; }
        public List<YahooDataRecord> Records { get; set; }
    }

    /// <summary>
    /// 数据元信息
    /// </summary>
    public class DataMetadata
    {
        public string Source { get; set; }
        public DateTime DownloadTime { get; set; }
        public string Symbol { get; set; }
        public string StartDate { get; set; }
        public string EndDate { get; set; }
        public int RecordCount { get; set; }
        public string DataType { get; set; }
        public string ApiVersion { get; set; }
    }
}